package com.rentapark.app;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import com.google.android.maps.GeoPoint;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.location.Geocoder;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import android.app.TimePickerDialog;
import android.widget.TimePicker;
import com.google.android.maps.GeoPoint;

import data.DB;
import android.location.Address;

//this activity is used when the usr wants to offer a aprking spot
public class RentScreen extends Activity{
	final RentScreen thisActivity = this;
	static final int TIME_DIALOG=1;
	static final int PROGRESS_DIALOG = 0;
	ProgressDialog progressDialog;
	private int mhour;
	private int mminute;
	private int mYear;
	private int mMonth;
	private int mDay;
	public String updateTime;
	public Date date2 = null;
	Date newDate=null;
	EditText AddressText;
	EditText timeText;
	String address;
	String tta;
	String prize;
	String comments;
	DB db_instance;
	GeoPoint pointToReturn;

	//this method handles server's response
	private final Handler handler = new Handler() {  
		public void handleMessage(Message msg) { 
			progressDialog.dismiss(); 
			Log.d("NewUSER","got response");
			String bundleResult = msg.getData().getString("RESPONSE"); 
			finish();
		} 
	}; 
//onCreate
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.rent);
		AddressText = (EditText) findViewById(R.id.EditText01);
		timeText=(EditText) findViewById(R.id.EditText02);
		final EditText prizeText=(EditText) findViewById(R.id.EditText03);
		final EditText commentsText=(EditText) findViewById(R.id.EditText05);
		db_instance=DB.getInstance();
		final Calendar c = Calendar.getInstance();


		DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = new Date();

		mhour = date.getHours();
		mminute = date.getMinutes();
		mYear=date.getYear();
		mMonth=date.getMonth();
		mDay=date.getDay();
		String time=dateFormat.format(date);
		Log.d("error",time);
		updateTime=time.substring(time.indexOf(" "));
		Log.d("secString",updateTime);
		timeText.setText(updateTime);
		timeText.setClickable(true);
		timeText.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				showDialog(TIME_DIALOG);
			}
		});
//this button is for the user to accept all entered information and perform the offer
		Button AddItemButton = (Button)this.findViewById(R.id.Offer);
		AddItemButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Geocoder geoCoder= new Geocoder(getBaseContext(),Locale.getDefault());
				//translating the address inserted to a geopoint
				try
				{
					List<Address> address= geoCoder.getFromLocationName(AddressText.getText().toString(), 8);
					if(address.size()>0)			
						pointToReturn =new GeoPoint((int)((address.get(0).getLatitude())*1E6), (int)((address.get(0).getLongitude())*1e6));
					else
					{
						Toast.makeText(RentScreen.this, "Address not found, try again", Toast.LENGTH_LONG).show();
						return;
					}


				} catch (IOException ex) {
					ex.printStackTrace();
					Toast.makeText(RentScreen.this, "Address not found, try again", Toast.LENGTH_LONG).show();
					return;

				}
				SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				Date now = new Date();
				now.setHours(mhour);
				now.setMinutes(mminute);
				String upd=dateFormat.format(now);
				tta=upd;
				prize=prizeText.getText().toString();
				comments=commentsText.getText().toString();
				//call offerPark method
				offerPark();



			}


		});
		//this button is for the user to choose an address from the map-
		//a map activity will open and there the user can choose a point for the parking spot
		Button mapButton = (Button)this.findViewById(R.id.map);
		mapButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Log.d("touched search button","true");
				Intent intent = new Intent(thisActivity, SearchAddress.class); 
				startActivity(intent);



			}


		});
	}
	//this method receives a geopoint and returns its address as a string
    protected String getReverseGeoCoder (GeoPoint point){
    	Geocoder geoCoder= new Geocoder(getBaseContext(),Locale.getDefault());
		String 	display ="";
		try
		{
			List<Address> address =geoCoder.getFromLocation(point.getLatitudeE6()/1E6, point.getLongitudeE6()/1E6, 1);
			if(address.size()>0)
			{

				for(int i=0;i<address.get(0).getMaxAddressLineIndex();i++)
				{		
					display += address.get(0).getAddressLine(i)+ "\n";
				}
			}
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		return display;
    }
    //onRestart- if the user chose a point from the map, then we convert the geopint into an address
	public void onRestart(){
		super.onRestart();
		Log.d("rentScreen","onRestart");
		SharedPreferences ref = getSharedPreferences("com.ruthy.parkApp",MODE_PRIVATE);

		String offer = ref.getString("parking_offer", "false");
		String add="";
		Log.d("rentScreen-offer",offer);
		if(offer.equals("true"))
		{
			Log.d("rentScreen-","works");
			int lati=Integer.parseInt(ref.getString("touchedLatitud", "0"));//get touched point latitud
			int longi=Integer.parseInt(ref.getString("touchedLongitud", "0"));//get touched point longitud
			GeoPoint point=new GeoPoint(lati,longi);
			Geocoder geoCoder= new Geocoder(getBaseContext(),Locale.getDefault());
			try
			{
				List<Address> address =geoCoder.getFromLocation(point.getLatitudeE6()/1E6, point.getLongitudeE6()/1E6, 1);
				if(address.size()>0)
				{
					for(int i=0;i<address.get(0).getMaxAddressLineIndex();i++)
					{		
						add += address.get(0).getAddressLine(i)+ "\n";
					}
					Log.d("rentScreen-","works2");
				}
				else
					Log.d("rentScreen-","address not found");
			} catch (IOException ex) {
				ex.printStackTrace();
			}		
			Log.d("rentScreen-address",add);
			AddressText=(EditText) findViewById(R.id.EditText01);
			AddressText.setText(add);
		}

		Log.d("rentScreen-editText",AddressText.getText().toString());
		SharedPreferences.Editor ed = ref.edit();
		ed.putString("parking_offer", "false");
		ed.putString("touchedLatitud", "0");
		ed.putString("touchedLongitud", "0");
		ed.commit();
	}
	//onCreateDialog method for the time picker
	protected Dialog onCreateDialog(int id) {
		Dialog dialog = null;;
		switch(id) {
		case TIME_DIALOG:
			return new TimePickerDialog(this,mTimeSetListener, mhour, mminute, false);

		default:
			dialog = null;
		}
		return dialog;
	}
	//listener for the time picker
	private TimePickerDialog.OnTimeSetListener mTimeSetListener =
			new TimePickerDialog.OnTimeSetListener() {
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			mhour = hourOfDay;
			mminute = minute;
			updatetime();
		}


	};
	//updatetime method for the time picker
	public void updatetime()
	{
		timeText.setText(
				new StringBuilder()
				.append(pad(mhour)).append(":")
				.append(pad(mminute))); 
	}
	//mthod for padding the time to a string
	private static String pad(int c) {
		if (c >= 10)
			return String.valueOf(c);
		else
			return "0" + String.valueOf(c);
	}
	//this method sends an http post  message to the server with all the info about the offered parking spot
	private void offerPark() { 
		// create HTTP response handler to handle the HTTP response
		// the response data is extracted from the HTTP message and then it is wrapped in a message
		// which  is passed to the android handler for handling
		final ResponseHandler<String> responseHandler = new ResponseHandler<String>() {   
			public String handleResponse(HttpResponse response) {           
				HttpEntity entity = response.getEntity();          
				String result = null; 
				try { 
					result = data.CommonUtilities.inputStreamToString(entity.getContent());

					Message message = new Message();     
					Bundle bundle = new Bundle();         
					bundle.putString("RESPONSE", result); 
					message.setData(bundle); 
					handler.sendMessage(message);  
				} catch (IOException e) { 
					Log.e("Class6",  " ", e); 
				} 
				return result; 
			} 
		}; 

		// start the progress dialog
		this.progressDialog = ProgressDialog.show(this, "executing", "    Performing Offer"); 

		// create and run the thread that perform the request and handle the response
		new Thread() {                          
			@Override 
			public void run() { 
				HttpClient httpclient = new DefaultHttpClient();
				Log.d("dbURL",db_instance.instanceDNS);
				String url="http://";
				url+=db_instance.instanceDNS;
				url+=":8080/ParkAndLetPark/ParkingOffer";
				Log.d("url is",url);
				HttpPost httppost = new HttpPost(url);
				//the http post message contains an xml with all the information needed for the server
				try {
					try{
						DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();

						DocumentBuilder docBuilder = builderFactory.newDocumentBuilder();
						//creating a new instance of a DOM to build a DOM tree.
						Document doc = docBuilder.newDocument();
						Element Response = doc.createElement("MSG_TYPE");
						Response.appendChild(doc.createTextNode("PARK_OFFER"));
						doc.appendChild(Response);


						Element User = doc.createElement("user_id");
						User.appendChild(doc.createTextNode(Double.toString(db_instance.userID)));
						Response.appendChild(User);

						Element ParkingSpot = doc.createElement("ParkingSpot");
						User.appendChild(ParkingSpot);

						Element latitud=doc.createElement("latitud");
						latitud.appendChild(doc.createTextNode(Double.toString(pointToReturn.getLatitudeE6()/1e6)) );
						ParkingSpot.appendChild(latitud);

						Element longitud=doc.createElement("longitud");
						longitud.appendChild(doc.createTextNode(Double.toString(pointToReturn.getLongitudeE6()/1e6)));
						ParkingSpot.appendChild(longitud);


						Element timeToAvailable=doc.createElement("timeToAvailable");
						timeToAvailable.appendChild(doc.createTextNode(tta));
						ParkingSpot.appendChild(timeToAvailable);

						Element prizeO=doc.createElement("prize");
						prizeO.appendChild(doc.createTextNode(prize));
						ParkingSpot.appendChild(prizeO);

						Element commentO=doc.createElement("comment");
						commentO.appendChild(doc.createTextNode(comments));
						ParkingSpot.appendChild(commentO);



						TransformerFactory factory = TransformerFactory.newInstance();
						Transformer transformer = factory.newTransformer();

						transformer.setOutputProperty(OutputKeys.INDENT, "yes");

						StringWriter sw = new StringWriter();
						StreamResult result = new StreamResult(sw);
						DOMSource source = new DOMSource(doc);
						transformer.transform(source, result);
						String xmlString = sw.toString();
						Log.d("xmlString","^^^^^^^^^^^^^^^^^^^^"+xmlString);


						StringEntity se = new StringEntity(xmlString); //XML as a string
						se.setContentType("text/xml"); //declare it as XML
						httppost.setEntity(se);
						Log.d("work","post executed");


						String response = httpclient.execute(httppost,responseHandler);
						Log.d("","************************************* "+response);

					}
					catch (ClientProtocolException e) {
						Log.e("LOGTAG", " " , e); 
					} catch (IOException e) {
						Log.e("LOGTAG", " " , e); 
					} catch (TransformerConfigurationException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}




				}
				catch(Exception e)
				{
					Log.e("LOGTAG", " " , e); 
				}
			}

		}.start(); 
	}


}
